package netTracker.network;


/**
 * A class for generating unique addresses.
 */
public class AddressFactory {

	PostOffice pobox;
	
	public AddressFactory(PostOffice pobox) {
		this.pobox = pobox;
	}

	/**
	 * Constructs an address from a given port by
	 * registering the address with the name server 
	 * and getting back a unique ID.
	 * @param port the port of the address
	 * @return the constructed address
	 * @throws PostalException
	 */
	public Address makeAddress(int port) throws PostalException{
		Message m = new Message("JOIN",new Address(port));
		try{	// Send a JOIN request to the name server:
			pobox.send (m, NameServer.NAMESERVER_ADDRESS);
			m = pobox.receive();
		}catch(Exception e){
			System.err.println("Error joining NameServer: "+e);
			throw new PostalException();
		}
		return m.getOtherAddr();
	}
	
	/**
	 * Constructs a new address from an old address by
	 * registering the address with the name server and 
	 * getting back a unique ID.
	 * @param oldAddress the old address
	 * @return the newly constructed address
	 * @throws PostalException
	 */
	public Address makeAddress(Address oldAddress) throws PostalException{
		Message m = new Message("JOIN",oldAddress);	// Create a JOIN request message
		try{	// Send a JOIN request to the name server:
			pobox.send (m, NameServer.NAMESERVER_ADDRESS);
			m = pobox.receive(); // Get back reply
		}catch(Exception e){
			System.err.println("Error joining NameServer: "+e);
			throw new PostalException();
		}
		return m.getOtherAddr();
	}
}
